<?php
namespace app\common\middleware;

use app\common\model\UserModel;
use app\common\service\Config;
use app\common\service\WxPublic;

class WechatAuth{
    public function handle($request, \Closure $next)
    {
        // 事件监听处理
        $current_url = app()->request->url(true);
        $current_url_arr = explode('/',$current_url);
        $module_name = $current_url_arr[3]??'';
        if($module_name=='admin' || $module_name=='api' || $module_name=='pay' || $module_name=='question'){

        }else{
            $session_user_info = session('user_info');
            if(empty($session_user_info) || empty($session_user_info['id'])){
                $current_url = $request->url(true);
                $code = $request->get('code');
                if($code){
                    //获取网页access_token
                    $auth_info = WxPublic::getWebAccessToken($code);
                    $access_token = $auth_info['access_token']??'';
                    $unionid = $auth_info['unionid']??'';
                    $openid = $auth_info['openid']??'';
                    $where = [];
                    $where[] = ['wx_openid','=', $openid];
                    if(!empty($unionid)){
                        $where[] = ['wx_unionid','=',$unionid];
                    }
                    $user_model = UserModel::whereOr($where)->find();
                    if(empty($user_model)){
                        //获取用户信息
                        $wx_user_info = WxPublic::actToUserInfo($access_token,$openid);
                        //绑定邀请者
//                if(!empty($req_code)){
//                    UserModel::$req_user_model =  UserModel::where(['req_code'=>$req_code])->find();
//                }
                        $user_model = new UserModel();
                        //创建用户
                        $user_model->setAttrs([
                            'wx_openid'=>$wx_user_info['openid'],
                            'wx_unionid'=> $unionid,
                            'name'=>$wx_user_info['nickname'],
                            'sex'=>$wx_user_info['sex'],
                            'avatar'=>$wx_user_info['headimgurl'],
                        ]);
                        $user_model->save();
                    }
                    //保存session
                    session('user_info',[
                        'id'=>$user_model['id'],
                        'name'=>$user_model['name'],
                        'openid'=>$openid,
                        'access_token'=>$access_token,
                    ]);

                }else{
                    $redirect_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.Config::wechat('wx_web','app_id').'&redirect_uri='.$current_url.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
                    return redirect($redirect_url);
                }
            }
        }


        return $next($request);
    }
}